﻿using HtmlAgilityPack;
using PidKeyReptile.Desktop.Model;
using PidKeyReptile.Desktop.Pages.Crawler;
using RestSharp;
using SqlSugar;
using Stylet;
using StyletIoC;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace PidKeyReptile.Desktop.Helper
{
    public class GetWeb
    {
        public CrawlerManagerViewModel _crawler;

        public SqlSugarClient Db;

        public  List<GatherKey> KeyList;

        public GetWeb()
        {
            Db = GetInstance();
        }
        public GetWeb(CrawlerManagerViewModel crawler)
        {
            Db = GetInstance();
            _crawler = crawler;
            KeyList = new List<GatherKey>();
        }


        public async Task<List<string>> ParseAsync(string data)
        {
            List<string> list = new List<string>();

            string RegexStr = @"([A-Z1-9]{5})-([A-Z1-9]{5})-([A-Z1-9]{5})-([A-Z1-9]{5})-([A-Z1-9]{5})";
            var res = Regex.Matches(data, RegexStr);
            foreach (var item in res)
            {
                //判断秘钥是否存在
                bool isAny = await Db.Queryable<GatherKey>().Where(it => it.ActionCode == item.ToString()).AnyAsync();
                if (!isAny)
                {
                    list.Add(item.ToString());
                    KeyList.Add(new GatherKey
                    {
                        ActionCode = item.ToString(),
                        UpTime = DateTime.Now,
                    });
                }
                else
                {
                    _crawler.LogText += ($"{DateTime.Now}---{item}存在重复，不入库\r\n");
                    Console.WriteLine($"{DateTime.Now}---{item}存在重复，不入库");
                }
            }
            return list;
        }

        public HtmlDocument GetHtml(string url, string cookie)
        {
            HtmlDocument html = new HtmlDocument();
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
                request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36 Edg/89.0.774.50";
                request.Headers.Add("cookie", cookie);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                html.LoadHtml(retString);
                return html;
            }
            catch (Exception ex)
            {
                return html;
            }
        }

        public SqlSugarClient GetInstance()
        {
            //创建数据库对象
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = AppConfigurtaionServices.Configuration["ConnectionStrings:Mysql"],//连接符字串
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute//从特性读取主键自增信息
            });

            //添加Sql打印事件，开发中可以删掉这个代码
            db.Aop.OnLogExecuting = (sql, pars) =>
            {
                //Console.WriteLine(sql);
            };
            return db;
        }
    }
}
